from flask import g
from flask import request
from flask import session, jsonify
from flask import url_for

from info import constants
from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue
from info import redis_store
import logging
from flask import current_app
from flask import render_template

# 功能分析：新闻列表局部刷新，那么就需要ajax请求，那就需要定义路由视图
# 请求方式：get
# 请求路径：newslist
# 请求参数：cid,page,per_page
# 返回数据：data数据


@index_blue.route('/newslist')
def news_list():

    cid = request.args.get('cid')
    page = request.args.get('page')
    per_page = request.args.get('per_page')

    # 数据类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10

    # 获取新闻
    try:
        filters = [News.status == 0]
        if cid != '1':
            filters.append(News.category_id == cid)

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取新闻数据失败')

    # 按页取数据属性分析
    totalpage = paginate.pages
    currentpage = paginate.page
    items = paginate.items

    newslist = []
    for item in items:
        newslist.append(item.to_dict())

    # data = {
    #     'totalpage':totalpage,
    #     'currentpage':currentpage,
    #     'newslist':newslist
    # }

    return jsonify(errno=RET.DATAERR,errmsg='获取成功',newsList = newslist,totalPage=totalpage,currentPage=currentpage)



@index_blue.route("/")
@user_login_data
def index():

    # 获取用户登陆状态
    # user_id = session.get('user_id')
    # user = None
    # # 判断用户是否存在,存在获取用户信息
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # user_dict = {}
    # if user:
    #     user_dict = {
    #         'id':user.id,
    #         'nick_name':user.nick_name
    #     }
    # 模板类中已经定义了方法获取用户信息，所以可以注释上面信息

    #根据点击量，获取前10条新闻,对象
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取热门新闻失败')
    click_news_list = []
    for new in news:
        click_news_list.append(new.to_dict())

    # 主页面分类
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取新闻分类')
    # 将对象列表转化成字典列表
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())


    # 添加到前端页面的数据
    data = {
        'user_info':g.user.to_dict() if g.user else '',
        'click_news_list':click_news_list,
        'category_list':category_list
    }

    return render_template('news/index.html',data = data)

@index_blue.route('/favicon.ico')
def web_logo():

    return current_app.send_static_file('news/favicon.ico')